﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsQuestionBoardTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Question Business Object
    /// </summary>

    public class Questions : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected Questions() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the Question.
        /// </summary>
        public int QuestionID
        {
            get { return _questionID; }
            set
            {
                if (_questionID != value)
                {
                    if (OnPropertyChanging("QuestionID", _questionID, value))
                    {
                        int oldValue = _questionID;
                        _questionID = value;

                        OnPropertyChanged("QuestionID", oldValue, value);
                    }
                }
            }
        }  private int _questionID = -1;

        /// <summary>
        /// JobID.
        /// </summary>
        public string JobID
        {
            get { return _jobID; }
            set
            {
                if (_jobID != value)
                {
                    if (OnPropertyChanging("JobID", _jobID, value))
                    {
                        string oldValue = _jobID;
                        _jobID = value;
                        OnPropertyChanged("JobID", oldValue, value);
                    }
                }
            }
        }  private string _jobID = null;


        /// <summary>
        /// CompanyID.
        /// </summary>
        public int CompanyID
        {
            get { return _companyID; }
            set
            {
                if (_companyID != value)
                {
                    if (OnPropertyChanging("CompanyID", _companyID, value))
                    {
                        int oldValue = _companyID;
                        _companyID = value;
                        OnPropertyChanged("CompanyID", oldValue, value);
                    }
                }
            }
        }  private int _companyID = -1;


        /// <summary>
        /// Question.
        /// </summary>
        public string Question
        {
            get { return _question; }
            set
            {
                if (_question != value)
                {
                    if (OnPropertyChanging("Question", _question, value))
                    {
                        string oldValue = _question;
                        _question = value;
                        OnPropertyChanged("Question", oldValue, value);
                    }
                }
            }
        }  private string _question = null;


        /// <summary>
        /// Date/time at which the Question was created.
        /// </summary>
        public DateTime? QuestionDate
        {
            get { return _questionDate; }
            set
            {
                if (_questionDate != value)
                {
                    if (OnPropertyChanging("QuestionDate", _questionDate, value))
                    {
                        DateTime? oldValue = _questionDate;
                        _questionDate = value;
                        OnPropertyChanged("QuestionDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _questionDate = null;


        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty Question object.
        /// </summary>
        public static Questions CreateNew()
        {
            Questions obj = new Questions();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.QuestionDate = DateTime.Now;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static Questions CreateNew(QuestionCollection collection)
        {
            Questions obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (Questions question in collection)
            {
                if (question.QuestionID < minVal)
                    minVal = question.QuestionID;
            }
            obj.QuestionID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllQuestion

        /// <summary>
        /// Returns a collection of all Question.
        /// </summary>
        public static QuestionCollection GetAllQuestion()
        {
            QuestionBoardsTableAdapter adapter = new QuestionBoardsTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            
            dsQuestionBoard.QuestionBoardsDataTable tbl = adapter.GetData(null);

            QuestionCollection list = new QuestionCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsQuestionBoard.QuestionBoardsRow row in tbl.Rows)
                {
                    Questions question = new Questions();
                    RelationalToObject(question, row);
                    list.Add(question);
                }
            }

            return (list);
        }

        #endregion

        #region GetQuestionByID

        /// <summary>
        /// Returns an Question object for the specified 'QuestionID' or null if no Question with the specified parameter(s) exists.
        /// </summary>
        public static Questions GetQuestionByID(int questionid)
        {
            QuestionBoardsTableAdapter adapter = new QuestionBoardsTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsQuestionBoard.QuestionBoardsDataTable tbl = adapter.GetData(questionid);

            if (tbl.Rows.Count == 1)
            {
                Questions question = new Questions();
                RelationalToObject(question, tbl.Rows[0]);
                return (question);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'questionid' returned more than one record.");

            return (null);
        }

        #endregion

        #region GetAllQuestionByJobID

        /// <summary>
        /// Returns a collection of all Question.
        /// </summary>
        public static QuestionCollection GetAllQuestionByJobID(string jobid)
        {
            QuestionBoardsTableAdapter adapter = new QuestionBoardsTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsQuestionBoard.QuestionBoardsDataTable tbl = adapter.GetDataByJobID(jobid);

            QuestionCollection list = new QuestionCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsQuestionBoard.QuestionBoardsRow row in tbl.Rows)
                {
                    Questions question = new Questions();
                    RelationalToObject(question, row);
                    list.Add(question);
                }
            }

            return (list);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified Question.
        /// </summary>
        public static void Update(Questions obj)
        {
            bool updateQuestion = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateQuestion = (obj.ObjState != ObjectState.Unchanged);

                if (!updateQuestion)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsQuestionBoard.QuestionBoardsDataTable tbl = null;
            if (updateQuestion)
            {
                QuestionBoardsTableAdapter adapter = new QuestionBoardsTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();

                tbl = new dsQuestionBoard.QuestionBoardsDataTable();
                dsQuestionBoard.QuestionBoardsRow row = tbl.NewQuestionBoardsRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (QuestionID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("QuestionID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                if ((Question == null) || (Question.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("Question", "Question is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("Question: QuestionID={0}, Question={1}", QuestionID, Question));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more Question objects.
    /// </summary>

    public class QuestionCollection : List<Questions>
    {
        #region Types

        public class UserComparer : IComparer<Questions>
        {
            public int Compare(Questions q1, Questions q2)
            {
                return (String.Compare(q1.Question, q2.Question));
            }
        }

        #endregion

        #region Public Methods

        #region FindByQuestionID

        public Questions FindByQuestionID(int questionID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].QuestionID == questionID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindQuestionByQuestion

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public Questions FindQuestionByQuestion(string question)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].Question == question)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion
    }
}
